<template>
  <!-- 购物车列表 -->
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="item in cartInfo.cartInfoList" :key="item.id">
          <!-- 选择框 -->
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="item.isChecked===1" @click="changeIschecked(item)" />
          </li>
          <!-- 图片和名称 -->
          <li class="cart-list-con2">
            <img :src="item.imgUrl" />
            <div class="item-msg">
              {{item.skuName}}
            </div>
          </li>
          <!-- 价格 -->
          <li class="cart-list-con4">
            <span class="price">{{item.skuPrice}}</span>
          </li>
          <!-- 数量和加减 -->
          <li class="cart-list-con5">
            <a class="mins" @click="sub(item)">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="item.skuNum"
              minnum="1"
              class="itxt"
              @blur="changeInputNum($event,item)"
            />
            <a class="plus" @click="add(item)">+</a>
          </li>
          <!-- 总价 -->
          <li class="cart-list-con6">
            <span class="sum">{{item.skuPrice * item.skuNum}}</span>
          </li>
          <!-- 操作 -->
          <li class="cart-list-con7">
            <a class="sindelet" @click="deleteCartGood(item.skuId)">删除</a>
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" :checked="isAllChecked&&cartInfoList.length>0" @click="changeIsAllChecked" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="deleteAllCartGood">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择&nbsp;<span>{{totalChecked}}</span>&nbsp;件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{totalPrice}}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
// 引入lodash，用于加减商品数量时的节流
import throttle from 'lodash/throttle'
export default {
  name: "Cart",
  mounted(){
    // 获取购物车数据
    this.getData()
  },
  methods:{
    // 获取购物车数据
    getData(){
      this.$store.dispatch('getCartList')
    },
    // 删除购物车商品
    async deleteCartGood(skuId){
      try {
        await this.$store.dispatch('deleteCartGood',skuId)
        // 重新获取数据更新页面
        this.getData()
      } catch (error) {
        alert(error.message)
      }
    },
    // 删除购物车中所有选中的商品
    deleteAllCartGood(){
      this.cartInfoList.forEach(async it=>{
        try {
          await this.$store.dispatch('deleteCartGood',it.skuId)
          // 重新获取数据更新页面
          this.getData()
          } catch (error) {
            alert(error.message)
          }
      })
    },
    // 改变单个商品是否选中
    async changeIschecked(item){
      // 切换isChecked的状态
      if(item.isChecked) item.isChecked=0
      else item.isChecked=1
      try {
        // 通知vuex发送信息
        await this.$store.dispatch('changeIschecked',{skuId:item.skuId,isChecked:item.isChecked})
      } catch (error) {
        alert(error.message)
      }
    },
    // 改变全部商品是否被选中
    changeIsAllChecked(){
      if(this.isAllChecked){
        // 将商品列表中的所有商品isChecked置零
        this.cartInfoList.forEach(async it=>{
          it.isChecked=0
          try {
            // 给服务器发送信息更改isChecked
            await this.$store.dispatch('changeIschecked',{skuId:it.skuId,isChecked:it.isChecked})
          } catch (error) {
            alert(error.message)
          }
        })
      }else{
        // 将商品列表中的所有商品isChecked置1
        this.cartInfoList.forEach(async it=>{
          it.isChecked=1
          try {
            // 给服务器发送信息更改isChecked
            await this.$store.dispatch('changeIschecked',{skuId:it.skuId,isChecked:it.isChecked})
          } catch (error) {
            alert(error.message)
          }
        })
      }
    },
    // 减少购物车某个商品数量------节流（在一定的时间内，函数只会执行一次）
    sub:throttle(async function(item){
        item.skuNum--
        if(item.skuNum<1){
          item.skuNum=1
          try {
            await this.$store.dispatch('addGoodOrUpdate',{skuId:item.skuId,skuNum:0})
            // 更新数据
            this.getData()
          } catch (error) {
            alert(error.message)
          }
        }else{
          try {
            await this.$store.dispatch('addGoodOrUpdate',{skuId:item.skuId,skuNum:-1})
            // 更新数据
            this.getData()
          } catch (error) {
            alert(error.message)
          }
        }
      },100),
    // 添加购物车某个商品数量----节流
    add:throttle(async function(item){
      item.skuNum++
      try {
        await this.$store.dispatch('addGoodOrUpdate',{skuId:item.skuId,skuNum:1})
      } catch (error) {
        alert(error.message)
      }
    },100),
    // 手动修改购物车某个商品数量
    async changeInputNum(e,item){
      // 接口要求正数表示加，负数表示减
      let num = e.target.value - item.skuNum
      // 判断用户输入是否符合要求
      if(isNaN(e.target.value*1)||e.target.value<1){
        num = 0
        // 修改当前显示值
        e.target.value = item.skuNum
      }
      else{
        num = parseInt(num)
        // 修改当前显示值
        e.target.value = parseInt(e.target.value)
      }
      try {
        await this.$store.dispatch('addGoodOrUpdate',{skuId:item.skuId,skuNum:num})
      } catch (error) {
        alert(error.message)
      }
    }
  },
  computed:{
    ...mapGetters(['cartInfo']),
    cartInfoList(){
      return this.cartInfo.cartInfoList || []
    },
    // 全部已选中商品总价
    totalPrice(){
      let sum = 0
      // this.cartInfo.cartInfoList.forEach(it => {
      this.cartInfoList.forEach(it => {
        if(it.isChecked===1) sum+=it.skuNum*it.skuPrice
      });
      return sum
    },
    // 选中了多少件商品
    totalChecked(){
      let sum = 0
      this.cartInfoList.forEach(it => {
        if(it.isChecked===1) sum++
      });
      return sum
    },
    // 全选按钮
    isAllChecked(){
      return this.cartInfoList.every(it=>it.isChecked===1)
    }
  }
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }
          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }
        .cart-list-con6 {
          width: 10%;
          .sum {
            font-size: 16px;
          }
        }
        .cart-list-con7 {
          width: 13%;
          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;
    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;
      span {
        vertical-align: middle;
      }
      input {
        vertical-align: middle;
      }
    }
    .option {
      padding: 10px;
      overflow: hidden;
      float: left;
      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }
    .money-box {
      float: right;
      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }
      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;
        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }
      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>